<template>
  <transition name="fade">
    <div :class="['alert-tip', 'text-14', type]" v-if="description">
      <span class="description" v-html="description"/>
      <span class="close-alert cursor-pointer" @click="close">&times;</span>
    </div>
  </transition>
</template>

<script>
  import { eventBus } from '../../eventbus/eventbus';

  export default {
    name: 'BaseAlertTip',
    data() {
      return {
        description: '',
        type: 'info',
        duration: 3,
        timer: null,
      };
    },
    methods: {
      close() {
        this.description = '';
        this.type = 'info';
        this.duration = 3;

        if (this.timer) {
          clearTimeout(this.timer);
          this.timer = null;
        }
      },
      countDownHide() {
        if(this.duration !== 0){
          this.timer = setTimeout(() => {
            this.close();
          }, this.duration * 1000);
        }
      }
    },
    mounted() {
      /**
       * alert事件将弹出基础提示框
       *
       * @param description 提示内容
       * @param paramObject 参数对象
       *
       * type 消息类型 用于显示图标和背景色 图标尚未添加  默认值： 'info' 参考值：'info'、'success'、'warning'、'error'
       * duration 可以控制关闭的时间间隔，默认值： 3  单位/s, 如果设置为0，则不会自动关闭
       */

      eventBus.on('alert', (description, paramObject) => {
        this.close();
        this.description = description;
        this.type = paramObject?.type ?? this.type;
        this.duration = paramObject?.duration ?? this.duration;
        this.countDownHide();
      });
    },
    destroyed() {
      eventBus.off('alert');
    }
  };
</script>

<style scoped>
  .fade-enter-active {
    animation: fade-in .5s;
  }

  .fade-leave-active {
    animation: fade-in .5s reverse;
  }

  .alert-tip {
    color: #ffffff;
    opacity: .92;
    transition: .3s linear;
    position: fixed;
    z-index: 1080;
    top: 40px;
    left: 50%;
    display: flex;
    justify-content: space-between;
    transform: translateX(-50%);
    width: 50%;
    padding: 12px 30px;
    border-radius: 5px;
    box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.25);
    -webkit-box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.25);
  }

  .alert-tip:hover {
    opacity: 1;
  }

  .description {
    margin: 0 auto;
  }

  .close-alert {
    font-weight: bold;
  }

  .close-alert:hover {
    transform: translateY(-1px);
  }

  .info {
    background-color: #909399;
  }

  .success {
    background-color: #67c23a;
  }

  .warning {
    background-color: #e6a23c;
  }

  .error {
    background-color: #f56c6c;
  }

  @media (max-width: 686px) {
    .alert-tip {
      width: 90%;
    }
  }

  @keyframes fade-in {
    from {
      opacity: 0;
    }
    to {
      opacity: .92;
    }
  }

  @-webkit-keyframes fade-in {
    from {
      opacity: 0;
    }
    to {
      opacity: .92;
    }
  }
</style>